package com.cate.controller.user;

import com.cate.constants.JwtClaimsConstant;
import com.cate.pojo.dto.UserLoginDTO;
import com.cate.pojo.entity.User;
import com.cate.pojo.vo.UserLoginVO;
import com.cate.properties.JwtProperties;
import com.cate.result.RestResponse;
import com.cate.service.UserService;
import com.cate.utils.JwtUtil;
import com.cate.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @CreateTime: 2023/7/31
 * @Author: <==lhd==>
 * @Description: 用户登录
 */

@RestController
@Slf4j
@RequestMapping("/user/user")
@Api(tags = "微信管理")
public class UserLoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation("微信登录")
    public RestResponse<UserLoginVO> UserLogin(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登录{}",userLoginDTO.getCode());

        // 威信登录
        final User user = userService.wxLogin(userLoginDTO);

        // 创建token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();

        return ResultUtil.success(userLoginVO);
    }
}
